var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/help/common.tsx
var common_exports = {};
__export(common_exports, {
  getHelpBeforeOpen: () => getHelpBeforeOpen,
  useCtx: () => useCtx,
  useHelp: () => useHelp,
  useTabItems: () => useTabItems,
  useTabKey: () => useTabKey
});
module.exports = __toCommonJS(common_exports);
var import_react = __toESM(require("react"));
var import_baseComponent = require("../../baseComponent");
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var import_query_panel = require("../query-panel");
var import_service = require("./service");
function flatTreeRow(tree) {
  return tree.reduce((arr, { children, disabled, ...c }) => {
    if (disabled) {
      return [...arr, ...flatTreeRow(children || [])];
    }
    return [...arr, import_util.iup.parseJson(c.row), ...flatTreeRow(children || [])];
  }, []);
}
function useHelp(props) {
  const {
    valueField,
    userCodeField,
    clientSqlFilter,
    infoRightUIContainerID,
    helpId,
    labelField,
    modalProps,
    footer,
    onBeforeOpen,
    showList,
    checkStrictly,
    treeDisabledLevel = 0,
    onlySelectedFinally = false,
    ...helpProps
  } = props;
  const sqlFilter = (0, import_util.useRefCallback)(async () => {
    if (import_util.iup.isFunction(clientSqlFilter)) {
      let _helpId = helpId;
      if (import_util.iup.isFunction(_helpId)) {
        _helpId = await _helpId();
      }
      return await clientSqlFilter({ helpId: _helpId });
    }
    return clientSqlFilter;
  });
  const cacheHelpInfo = (0, import_react.useRef)({ data: null, p: null });
  helpProps.onBeforeOpen = (0, import_util.useRefCallback)(async () => {
    const [status, helpInfo] = await getHelpBeforeOpen({ helpId, onBeforeOpen, cacheHelpInfo }, props);
    if (import_util.iup.isObject(helpInfo)) {
      return { ...helpInfo, activeTabKey: await (0, import_service.getActiveTabKey)({ helpId }) };
    }
    return status;
  });
  helpProps.request = (0, import_react.useMemo)(() => {
    return async (params) => {
      const filterValue = await sqlFilter();
      return (0, import_service.getHelpList)({
        ...params,
        helpId,
        clientSqlFilter: filterValue,
        infoRightUIContainerID
      });
    };
  }, [helpId, infoRightUIContainerID, sqlFilter]);
  helpProps.selectedRequest = (0, import_util.useRefCallback)(({ codes }) => {
    return (0, import_service.getSelectedData)({ helpId, codes });
  });
  if (helpId) {
    helpProps.valueField = valueField;
    helpProps.userCodeField = userCodeField;
    helpProps.labelField = labelField;
    helpProps.getHelpInfo = () => cacheHelpInfo.current.data || {};
    helpProps.contentParams = {
      footer,
      helpId,
      valueField,
      treeDisabledLevel,
      onlySelectedFinally,
      checkStrictly,
      labelField: helpProps.labelField,
      treeListRequest: () => (0, import_service.getTreeList)({ helpId, clientSqlFilter }),
      commonRequest: async (params) => {
        const filterValue = await sqlFilter();
        return (0, import_service.getCommonList)({
          ...params,
          helpId,
          clientSqlFilter: filterValue,
          infoRightUIContainerID
        });
      },
      recentlyRequest: async (params) => {
        const filterValue = await sqlFilter();
        return (0, import_service.getRecentlyList)({
          ...params,
          helpId,
          clientSqlFilter: filterValue,
          infoRightUIContainerID
        });
      }
    };
    if (helpProps.modal === false) {
      helpProps.loadByFocus = true;
    } else {
      helpProps.modal = true;
    }
  } else {
    console.warn(`${props._id || ""} helpId is undefined`);
  }
  return [helpProps, modalProps];
}
function useTabKey(initTabs) {
  const {
    observer,
    contentParams: { helpId, activeTabKey }
  } = (0, import_react.useContext)(import_functionalComponent.HelpContext);
  const [activeKey, setActiveKey] = (0, import_react.useState)(() => {
    if (import_util.iup.isFunction(initTabs)) {
      const tabs = initTabs();
      return activeTabKey && tabs.includes(activeTabKey) ? activeTabKey : tabs[0];
    }
    return activeTabKey ?? "0";
  });
  const saveTabKey = (0, import_util.useRefCallback)(() => {
    (0, import_service.saveActiveTabKey)({ helpId, activeTabKey: activeKey }).then();
  });
  (0, import_react.useEffect)(() => {
    return observer.subscribe(saveTabKey, "beforeDestroy");
  }, []);
  return [activeKey, setActiveKey];
}
function useCtx(multiple) {
  const {
    ok,
    contentParams: {
      helpId,
      treeListRequest,
      checkStrictly,
      treeDisabledLevel = 0,
      onlySelectedFinally = false,
      getFieldValue,
      showList,
      showTree,
      showRecently,
      querySearchList
    },
    locale,
    randomKey
  } = (0, import_react.useContext)(import_functionalComponent.HelpContext);
  const [searchOpen, setSearchOpen] = (0, import_react.useState)(false);
  const rightTable = (0, import_react.useRef)();
  const [activeKey, setActiveKey] = useTabKey(() => {
    const tabs = [];
    showList && tabs.push("listStyle");
    showTree && tabs.push("treeStyle");
    tabs.push("commonData");
    showRecently && tabs.push("recentlyUsed");
    return tabs;
  });
  const getTable = (0, import_util.useRefCallback)(() => {
    const api = import_util.iup.getCmpApi(`${helpId}_${randomKey}_${activeKey}`);
    if (activeKey === "treeStyle") {
      api.getSelectedData = () => api.getSelectedNodes().map(({ row }) => import_util.iup.parseJson(row));
      api.getRows = () => flatTreeRow(api.getNodes());
    }
    return api;
  });
  const getResult = (0, import_util.useRefCallback)(() => {
    if (multiple) {
      const codeValue = [];
      const result = rightTable.current.getApi().getRows().map((r) => {
        codeValue.push(getFieldValue(r));
        return {
          value: getFieldValue(r),
          label: getFieldValue(r, "label"),
          origin: { ...r }
        };
      });
      (0, import_service.addRecentlyData)({ helpId, codeValue: codeValue.join() });
      return result.length > 0 ? result : void 0;
    } else {
      const row = getTable().getSelectedData()[0];
      if (row) {
        (0, import_service.addRecentlyData)({ helpId, codeValue: getFieldValue(row) });
        return { value: getFieldValue(row), label: getFieldValue(row, "label"), origin: { ...row } };
      }
      return void 0;
    }
  });
  const onSearch = (0, import_util.useRefCallback)((searchObj) => {
    var _a, _b, _c;
    if (activeKey === "listStyle") {
      (_a = getTable()) == null ? void 0 : _a.query(searchObj);
    } else if (activeKey === "treeStyle") {
      (_b = getTable()) == null ? void 0 : _b.filterTreeNode(searchObj.keyword || "");
    } else {
      (_c = getTable()) == null ? void 0 : _c.filter(searchObj.keyword || "");
    }
  });
  const showAdvancedSearch = activeKey === "listStyle" && querySearchList;
  const tabBarExtraContent = /* @__PURE__ */ import_react.default.createElement("div", { style: { float: "right", marginRight: 20, display: "flex", alignItems: "center", whiteSpace: "nowrap" } }, showAdvancedSearch && /* @__PURE__ */ import_react.default.createElement("a", { style: { marginRight: 8 }, onClick: () => setSearchOpen(!searchOpen) }, searchOpen ? "收起" : "高级", /* @__PURE__ */ import_react.default.createElement(
    import_util.DownOutlined,
    {
      style: {
        marginLeft: "0.3em",
        transition: "all 0.3s ease 0s",
        transform: `rotate(${searchOpen ? "180deg" : 0})`
      }
    }
  )), /* @__PURE__ */ import_react.default.createElement(
    import_baseComponent.Search,
    {
      style: { width: 250 },
      size: "small",
      allowClear: true,
      placeholder: locale.searchPlaceholder,
      onSearch: (keyword) => onSearch({ keyword })
    }
  ));
  const getAdvancedSearch = () => {
    if (showAdvancedSearch && searchOpen) {
      return /* @__PURE__ */ import_react.default.createElement(
        import_query_panel.QueryPanel,
        {
          pageId: helpId,
          items: querySearchList,
          columns: 3,
          showAll: true,
          onSearch: (_, querysearch) => onSearch({ querysearch })
        }
      );
    } else {
      return null;
    }
  };
  const convertNode = (0, import_util.useRefCallback)((node) => {
    var _a;
    const newNode = {
      title: node.text,
      key: node.id,
      ...node,
      disabled: onlySelectedFinally && ((_a = node.children) == null ? void 0 : _a.length) || node.currentLevel <= treeDisabledLevel || node.disabled
    };
    if (newNode.disabled) {
      newNode.expanded = true;
    }
    return newNode;
  });
  const renderTreeList = (0, import_util.useRefCallback)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          height: "100%",
          border: "1px solid var(--border-color-split, #f0f0f0)",
          borderTop: 0,
          padding: "5px 0"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_functionalComponent.AsyncTree,
        {
          id: `${helpId}_${randomKey}_treeStyle`,
          checkable: multiple,
          checkStrictly,
          onDoubleClick: () => {
            !multiple && ok(getResult());
          },
          showFilter: false,
          request: treeListRequest,
          convertNode
        }
      )
    );
  });
  const changeCommonData = (0, import_util.useRefCallback)(async () => {
    var _a;
    const selectedData = getTable().getSelectedData();
    if (!selectedData.length) {
      import_functionalComponent.message.warning(locale.noSelected);
      return;
    }
    const action = activeKey === "commonData" ? import_service.deleteCommonData : import_service.addCommonData;
    const success = await action({
      helpId,
      codeValue: selectedData.map((d) => getFieldValue(d)).join()
    });
    if (success) {
      (_a = import_util.iup.getCmpApi(`${helpId}_${randomKey}_commonData`)) == null ? void 0 : _a.refreshData();
      import_functionalComponent.message.success(activeKey === "commonData" ? locale.removeCommonSuccess : locale.addCommonSuccess);
    }
  });
  return {
    activeKey,
    setActiveKey,
    tabBarExtraContent,
    advancedSearch: getAdvancedSearch(),
    rightTable,
    getTable,
    renderTreeList,
    changeCommonData,
    getResult
  };
}
function useTabItems({ renderTable }) {
  const {
    request,
    contentParams: { helpId, commonRequest, recentlyRequest, showTree, showList, showRecently },
    locale
  } = (0, import_react.useContext)(import_functionalComponent.HelpContext);
  return (0, import_react.useMemo)(() => {
    const tabTitle = (title) => /* @__PURE__ */ import_react.default.createElement("span", { style: { padding: "0 8px" } }, title);
    const innerItems = [];
    showList && innerItems.push({
      key: "listStyle",
      label: tabTitle(locale.List),
      children: renderTable("listStyle", request)
    });
    showTree && innerItems.push({
      key: "treeStyle",
      label: tabTitle(locale.Tree),
      children: renderTable("treeStyle")
    });
    innerItems.push({
      key: "commonData",
      label: tabTitle(locale.CommonUse),
      children: renderTable("commonData", commonRequest)
    });
    showRecently && innerItems.push({
      key: "recentlyUsed",
      label: tabTitle(locale.RecentlyUsed),
      children: renderTable("recentlyUsed", recentlyRequest)
    });
    return innerItems;
  }, [helpId]);
}
async function getHelpBeforeOpen({ helpId = "", onBeforeOpen, cacheHelpInfo }, props = {}) {
  if (onBeforeOpen) {
    const canOpen = await onBeforeOpen();
    if (canOpen === false) {
      return [false];
    }
  }
  if (cacheHelpInfo.current.data) {
    return [true, cacheHelpInfo.current.data];
  }
  if (!cacheHelpInfo.current.p) {
    cacheHelpInfo.current.p = (0, import_service.getHelpInfo)({ helpId });
  }
  const helpInfo = await cacheHelpInfo.current.p;
  if (helpInfo === false) {
    return [false];
  }
  if (props.valueField) {
    helpInfo.valueField = props.valueField;
  }
  if (props.labelField) {
    helpInfo.labelField = props.labelField;
  }
  if (props.userCodeField) {
    helpInfo.userCodeField = props.userCodeField;
  }
  if (props.hasOwnProperty("showList")) {
    helpInfo.showList = props.showList;
  }
  cacheHelpInfo.current.data = helpInfo;
  cacheHelpInfo.current.p = null;
  return [true, helpInfo];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getHelpBeforeOpen,
  useCtx,
  useHelp,
  useTabItems,
  useTabKey
});
